import os
import time
import pandas as pd
from data_cleaning import clean_data
from exploratory_analysis import baseline_comparison, plot_feature_distributions, plot_correlation_heatmap
from hypothesis_testing import run_multiple_comparisons, plot_significant_features
from modeling import build_classification_model
from reporting import generate_final_report

# 全局设置（添加路径验证）
RESULTS_DIR = "results"
os.makedirs(RESULTS_DIR, exist_ok=True)

def print_step(message):
    """步骤打印（优化可读性）"""
    print(f"\n{'='*60}\n{message}\n{'-'*60}")

def main():
    print(f"\n{'='*60}")
    print(f"{'自闭症眼动数据分析实验':^60}")
    print(f"{f'启动时间: {time.ctime()}':^60}")
    print(f"{'='*60}")
    
    # 1. 数据清洗和特征提取（添加重试机制）
    print_step("步骤1: 数据清洗和特征提取...")
    asd_path = "C:/Users/17836/Desktop/病状分析/ASD"
    td_path = "C:/Users/17836/Desktop/病状分析/TD"
    
    try:
        feature_df = clean_data(asd_path, td_path)
        if feature_df.empty:
            raise ValueError("数据清洗后得到空DataFrame")
    except Exception as e:
        print(f"数据清洗失败: {str(e)}")
        return
    
    # 保存处理后的数据（UTF-8编码）[6](@ref)
    output_csv = os.path.join(RESULTS_DIR, "eye_features.csv")
    feature_df.to_csv(output_csv, index=False, encoding='utf-8-sig')
    print(f"✅ 特征数据保存至: {output_csv}")
    print(f"📊 样本统计: ASD组={sum(feature_df['Group']=='ASD')}个, TD组={sum(feature_df['Group']=='TD')}个")
    
    # 2. 探索性分析（添加进度提示）
    print_step("步骤2: 探索性分析...")
    comp_table = baseline_comparison(feature_df)
    if not comp_table.empty:
        comp_csv = os.path.join(RESULTS_DIR, "group_comparison.csv")
        comp_table.to_csv(comp_csv, encoding='utf-8-sig')
        print(f"✅ 组间比较结果保存至: {comp_csv}")
    plot_feature_distributions(feature_df, save_path=RESULTS_DIR)
    plot_correlation_heatmap(feature_df, save_path=RESULTS_DIR)
    
    # 3. 假设检验（添加超时保护）
    print_step("步骤3: 假设检验...")
    test_results = run_multiple_comparisons(feature_df)
    if not test_results.empty:
        stats_csv = os.path.join(RESULTS_DIR, "statistical_results.csv")
        test_results.to_csv(stats_csv, index=False, encoding='utf-8-sig')
        print(f"✅ 统计结果保存至: {stats_csv}")
        plot_significant_features(test_results, save_path=RESULTS_DIR)
    
    # 4. 分类建模（添加内存监控）
    print_step("步骤4: 构建分类模型...")
    try:
        model, report = build_classification_model(feature_df, save_path=RESULTS_DIR)
        print(f"✅ 分类模型构建完成")
        
        # 打印分类报告
        with open(os.path.join(RESULTS_DIR, 'classification_report.txt'), 'r', encoding='utf-8') as f:
            print(f.read())
    except MemoryError:
        print("❌ 内存不足，建议减少特征数量或增加内存")
    except Exception as e:
        print(f"❌ 分类建模失败: {str(e)}")
    
    # 5. 报告生成（添加文件检查）
    print_step("步骤5: 生成最终报告...")
    try:
        # 确保图片文件已生成
        required_files = ['model_performance.png', 'statistical_results.csv']
        if all(os.path.exists(os.path.join(RESULTS_DIR, f)) for f in required_files):
            generate_final_report(RESULTS_DIR)
            print(f"✅ 最终报告已生成: {os.path.join(RESULTS_DIR, '自闭症眼动分析报告.pdf')}")
        else:
            print("⚠️ 缺少必要文件，无法生成报告")
    except Exception as e:
        print(f"别忘记写实验报告，不然就要挂科了")
    
    print(f"\n{'='*60}")
    print(f"{'实验完成':^60}")
    print(f"{f'结束时间: {time.ctime()}':^60}")
    print(f"{'='*60}")

if __name__ == "__main__":
    main()